import { App, Spin } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { ReactNode, useEffect, useMemo } from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { RouterProvider } from 'react-router-dom';
import { YmAliOssFilePathRuleProvider, YmConfigProvider } from 'ym-design';
import { request } from './api/request';
import { YmSafeEduAliOssConfig } from './common';
import './globalStyles/main.less';
import { store } from './redux/store';
import { bossRouter } from './routers/bossRouterConfig';
dayjs.locale('zh-cn');

function parseFromUrl() {
  // ?token=eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjE0ZTRiZTdlLWRmYjctNGVkNy1iMWE1LTU2ODZmNTZiMTZmNyJ9.1mkjziHmKcCmE9L5i3wZNtdaJ0yPxFwRPtfDSlc7J_XOgQfPNZxjZEPgncAAgfXjH-Msrqv0ptB73Q-KhUSDYA&gowhere=waitlisting/package
  // 读取到了参数
  if (process.env.processEnvDetail.NODE_ENV === 'developmentBoss') {
    // localStorage.setItem('insert-boss-token', '123');
    if (localStorage.getItem('insert-boss-token')) {
      localStorage.removeItem('insert-boss-token');
    }
    request.interceptors.request.use((config) => {
      const tk =
        'eyJjbGllbnRJZCI6ImNsaWVudElkIiwidHlwIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJ1c2VySW5mbyI6IntcInBob25lXCI6XCIxODY1ODg4ODg4MVwiLFwibG9naW5OYW1lXCI6XCJhZG1pblwiLFwidXNlck5hbWVcIjpcIui_kOiEieeuoeeQhuWRmFwifSIsImV4cCI6MTcyMzg4MDk2NSwiaWF0IjoxNzIzNzk0NTY1fQ.mu62cVMfGzOW4yxsQufdIGWewZSMYRyuF6vK_ap5OnQ';
      config.headers['Authorization'] = tk; //安全教育相关boss端token(boss端-菜单管理-嵌入地址为/manager/safe/goNewSafe开头的页面token)
      config.headers['Bosstk'] = tk; //其他业务boss端token (boss端-菜单管理-嵌入地址为/manager/page/toPage/newBoss开头的页面token)
      config.headers['ClientType'] = 'boss';
      return config;
    });
  } else {
    if (window.location.search) {
      const usp = new URLSearchParams(window.location.search);
      const gowhere = usp.get('gowhere');
      const token = usp.get('token');
      console.log('--嵌入token--gowhere--', token, gowhere);
      if (gowhere && token) {
        if (!localStorage.getItem('insert-boss-token')) {
          localStorage.setItem('insert-boss-token', token);
        }
        bossRouter.navigate(gowhere);
        request.interceptors.request.use((config) => {
          config.headers['Authorization'] = token;
          config.headers['Bosstk'] = token;
          config.headers['ClientType'] = 'boss';
          return config;
        });
      }
    }
  }
}

parseFromUrl();

const root = ReactDOM.createRoot(document.getElementById('root-boss') as HTMLElement);

function MyInit() {
  const { message } = App.useApp();

  useEffect(() => {
    console.log('执行顺序1');
    const id = request.interceptors.response.use(
      function (response) {
        console.log('成功了就会走这里么');
        return response;
      },
      (err: unknown) => {
        console.log(err, '检查一下报错内容');
        message.error(String(err).replace('AxiosError:', ''));
      },
    );
    return () => {
      request.interceptors.response.eject(id);
    };
  }, [message]);

  return <></>;
}

function AliProvider(props: { children: ReactNode }) {
  const value = useMemo(() => {
    return { ...YmSafeEduAliOssConfig };
  }, []);

  return <YmAliOssFilePathRuleProvider value={value}>{props.children}</YmAliOssFilePathRuleProvider>;
}

root.render(
  <YmConfigProvider input={{ autoComplete: 'off' }} theme={{ token: { colorPrimary: '#3E84E9' } }}>
    <App>
      <Provider store={store}>
        <AliProvider>
          <MyInit></MyInit>
          <RouterProvider router={bossRouter} fallbackElement={<Spin />} />
        </AliProvider>
      </Provider>
    </App>
  </YmConfigProvider>,
);
